package com.feijia.aijingjingus;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.OvershootInterpolator;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TabHost;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.feijia.aijingjingus.util.PreferencesUtils;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import com.prolificinteractive.materialcalendarview.OnDateSelectedListener;
import com.prolificinteractive.materialcalendarview.OnMonthChangedListener;
import com.timqi.sectorprogressview.ColorfulRingProgressView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.sharesdk.onekeyshare.OnekeyShare;
import github.hellocsl.cursorwheel.CursorWheelLayout;

import static com.feijia.aijingjingus.GlobalHelper.DaysBeforeOvulation;
import static com.feijia.aijingjingus.GlobalHelper.DetectionDatetime;
import static com.feijia.aijingjingus.GlobalHelper.FirstDay;
import static com.feijia.aijingjingus.GlobalHelper.GUserNum;
import static com.feijia.aijingjingus.GlobalHelper.Menstruation;
import static com.feijia.aijingjingus.GlobalHelper.ONE_DAY_MS;
import static com.feijia.aijingjingus.GlobalHelper.OvulationLength;
import static com.feijia.aijingjingus.GlobalHelper.PeriodLength;
import static com.feijia.aijingjingus.GlobalHelper.ShowLocalDetection;

public class detectionHistoryActivity extends AppCompatActivity {
    RelativeLayout relativeLayout4;
    LinearLayout ll_linearLayout;
    ImageButton imageButton4;
    private ListView listView;
    private TabHost tabHost;
    private DatePicker mDatePicker;
    private Calendar c;
    ScrollView scrollView1;
    private List<Map<String, Object>> historyData;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    final Context thisContext = this;
    final int CD = 2;
    static int countDown = 2;
    boolean selectingDate, showPicker;
    String NowDateStr;
    private RelativeLayout rlLoad, rlNoData, rlDataPicker;
    private TextView tvShowDate, tvShowDate2, tvDateDetail, tvPercent,textView19;
    private FrameLayout flCalendar, flCursorWheel;
    private List<WheelItemData> wheelItemData;
    CursorWheelLayout cwl;
    TimePickerView pvPickDay;
    Thread Ticker;
    public boolean exit = false;
    MaterialCalendarView mcv;
    ColorfulRingProgressView crpv;
    private SharedPreferences sp;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;
    Handler handler = new Handler();
    final Runnable runnableUi = new Runnable() {
        @Override
        public void run() {
            //更新界面
            int y = scrollView1.getScrollY();
            SimpleAdapter adapter = new SimpleAdapter(thisContext, historyData, R.layout.sample_detection_view,
                    new String[]{"value", "date", "img", "data"},
                    new int[]{R.id.value, R.id.date, R.id.resultimg, R.id.data});
            listView.setAdapter(adapter);
            rlLoad.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
            if (historyData.size() == 0)
                rlNoData.setVisibility(View.VISIBLE);
            listView.setFocusable(false);
            ViewGroup.LayoutParams params = listView.getLayoutParams();
            params.height = historyData.size() * 500;
            listView.setLayoutParams(params);
            scrollView1.smoothScrollTo(0, y);
        }

    };
    final Runnable updateDate = new Runnable() {
        @Override
        public void run() {

            mcv.setSelectedDate(c.getTime());
            mcv.setCurrentDate(c.getTime());
            tvShowDate.setText(NowDateStr);
        }

    };
    final Runnable updateDateDetail = new Runnable() {
        @Override
        public void run() {
            try {
                Date date = sdf.parse(NowDateStr);
                tvShowDate2.setText(SimpleDateFormat.getDateInstance().format(date));
                Calendar cl = Calendar.getInstance();
                cl.setTime(date);
                long nowDay = (cl.getTimeInMillis() / ONE_DAY_MS) % Menstruation;
                date = sdf.parse(FirstDay);
                cl.setTime(date);
                long firstDay = (cl.getTimeInMillis() / ONE_DAY_MS) % Menstruation;
                nowDay -= firstDay;
                if (nowDay < 0)
                    nowDay += Menstruation;
                cl.add(Calendar.DAY_OF_MONTH, PeriodLength);
                long firstDayAfterPeriod = (cl.getTimeInMillis() / ONE_DAY_MS) % Menstruation - firstDay;
                long firstDayOfOvulation = DaysBeforeOvulation;
                long lastDayOfOvulation = firstDayOfOvulation + OvulationLength;
                long lastDay = firstDay + Menstruation - firstDay;
                firstDay = 0;

                String str;
                int days;
                int PregnancyProbability = 15;
                System.out.println("nowDay:" + nowDay + "  firstDayAfterPeriod:" + firstDayAfterPeriod + "  firstDayOfOvulation:" + firstDayOfOvulation + "  lastDayOfOvulation:" + lastDayOfOvulation + "  lastDay:" + lastDay + "  firstDay:" + firstDay);
                if (nowDay >= firstDay && nowDay < firstDayAfterPeriod) {
                    days = (int) ((nowDay - firstDay)) + 1;
                    PregnancyProbability = 10;
                    str = String.format(getString(R.string.DayOfMenstrualPeriod_html), days);
                    //str = "This is the day <font color=\"#FF3366\">2</font> of the menstrual period.";
                    System.out.println(str);
                } else if (nowDay >= firstDayAfterPeriod && nowDay < firstDayOfOvulation) {
                    days = (int) ((firstDayOfOvulation - nowDay));
                    if (days == 1)
                        str = getString(R.string.DayBeforeOvulation_html);
                    else
                        str = String.format(getString(R.string.DaysBeforeOvulation_html), days);
                } else if (nowDay >= firstDayOfOvulation && nowDay < lastDayOfOvulation) {
                    days = (int) ((nowDay - firstDayOfOvulation)) + 1;
                    str = String.format(getString(R.string.DayOfOvulation_html), days);
                    PregnancyProbability = 90 - Math.abs(days - OvulationLength / 2) * 15;
                } else if (nowDay >= lastDayOfOvulation && nowDay < lastDay) {
                    days = (int) ((lastDay - nowDay));
                    str = String.format(getString(R.string.DaysBeforePeriod_html), days);
                } else {
                    days = (int) ((firstDay - nowDay));
                    if (days == 1)
                        str = getString(R.string.DayBeforePeriod_html);
                    else
                        str = String.format(getString(R.string.DaysBeforePeriod_html), days);
                }
                //str=""+days;
                tvDateDetail.setText(Html.fromHtml(str));
                ObjectAnimator crpvChange = ObjectAnimator.ofFloat(crpv, "Percent", crpv.getPercent(), PregnancyProbability).setDuration(500);
                crpvChange.start();
                //crpv.setPercent(PregnancyProbability);
                str = "" + PregnancyProbability + "%\n" + getString(R.string.PregnancyProbability);
                SpannableStringBuilder style = new SpannableStringBuilder(str);
                AbsoluteSizeSpan span = new AbsoluteSizeSpan(24, true);
                style.setSpan(span, 0, 2, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                tvPercent.setText(style);
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }
    };
    final Runnable beforeGetDate = new Runnable() {
        @Override
        public void run() {
            rlNoData.setVisibility(View.GONE);
            listView.setVisibility(View.GONE);
            rlLoad.setVisibility(View.VISIBLE);
        }

    };

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (GUserNum.equals(""))
            finish();
        setContentView(R.layout.activity_detection_history_layout);

//        if(PreferencesUtils.getString(this,PreferencesUtils.PREFERENCE_NAME).equals("男")){
//            imageButton4=(ImageButton)findViewById(R.id.imageButton4);
//            textView19=(TextView)findViewById(R.id.textView19);
//            textView19.setTextColor(getColor(R.color.womain_pink));
//            imageButton4.setImageDrawable(getDrawable(R.drawable.homepageman));
//            //        用户男性时修改UI背景色
//            relativeLayout4=(RelativeLayout)findViewById(R.id.relativeLayout4);
//            relativeLayout4.setBackground(getDrawable(R.drawable.top_bar_with_shadow_two));
//        }


        rlLoad = (RelativeLayout) findViewById(R.id.rlDataLoading);
        rlNoData = (RelativeLayout) findViewById(R.id.rlNoData);
        rlDataPicker = (RelativeLayout) findViewById(R.id.rlPickerDate);
        crpv = (ColorfulRingProgressView) findViewById(R.id.crpv);
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        //client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
        mcv = (MaterialCalendarView) findViewById(R.id.calendarView);
        mcv.setTopbarVisible(false);
        listView = (ListView) findViewById(R.id.allDetection);
        NowDateStr = sdf.format(new Date());
        tvShowDate = (TextView) findViewById(R.id.tvShowDate);
        tvShowDate.setText(NowDateStr);
        tvShowDate2 = (TextView) findViewById(R.id.tvShowDate2);
        tvDateDetail = (TextView) findViewById(R.id.tvDateDetail);
        tvPercent = (TextView) findViewById(R.id.tvPercent);
        scrollView1 = (ScrollView) findViewById(R.id.scrollView1);
        flCalendar = (FrameLayout) findViewById(R.id.flCalendar);
        flCursorWheel = (FrameLayout) findViewById(R.id.flCursorWheel);
        cwl = (CursorWheelLayout) findViewById(R.id.CursorWheelLayout);
        //mcv.setTileHeightDp(39);
        //mcv.setTileWidthDp(52);

        handler.post(updateDateDetail);

        Ticker = new Thread(new Runnable() {

            @Override
            public void run() {
                int cd;
                while (!exit) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    cd = countDown;
                    Log.v("showPicker", showPicker + "");
                    Log.v("countDown", countDown + "");
                    if (cd != 0 && !showPicker) {
                        countDown = (cd - 1);
                        handler.post(updateDate);
                        handler.post(updateDateDetail);
                        if (cd - 1 == 0) {
                            handler.post(beforeGetDate);

                            historyData = getData(NowDateStr);
                            handler.post(runnableUi);
                        }
                    }
                }
            }
        });
        Ticker.start();


        if (FirstDay == null || FirstDay.isEmpty() || Menstruation == 0 || PeriodLength == 0) {
            sp = this.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
            FirstDay = sp.getString("FirstDay", "");
            Menstruation = sp.getInt("Menstruation", 0);
            PeriodLength = sp.getInt("PeriodLength", 0);
        }

        /*
        new Thread(new Runnable() {
            @Override
            public void run() {
                listView = (ListView) findViewById(R.id.allDetection);
                historyData = getData();
                handler.post(runnableUi);
            }
        }).start();
*/

        //Date curDate = new Date(System.currentTimeMillis());
        //etTime .setText(curDate.toString());
        mcv.setOnDateChangedListener(new OnDateSelectedListener() {
            @Override
            public void onDateSelected(@NonNull MaterialCalendarView widget, @NonNull CalendarDay date, boolean selected) {

            }
        });
        // 获取当前的年、月、日、小时、分钟
        c = Calendar.getInstance();
        mDatePicker = (DatePicker) findViewById(R.id.datePicker);
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);


        mDatePicker.init(year, month, day, new DatePicker.OnDateChangedListener() {

            public void onDateChanged(DatePicker view, int year,
                                      int monthOfYear, int dayOfMonth) {
                c.set(year, monthOfYear, dayOfMonth);
                SetCursorWheel(c);
                countDown = CD;
                NowDateStr = sdf.format(c.getTime());
                tvShowDate.setText(NowDateStr);
                handler.post(updateDateDetail);
            }
        });
        mcv.setOnDateChangedListener(new OnDateSelectedListener() {
            @Override
            public void onDateSelected(@NonNull MaterialCalendarView widget, @NonNull CalendarDay date, boolean selected) {
                if (selected) {
                    c.set(date.getYear(), date.getMonth(), date.getDay());
                    mDatePicker.updateDate(date.getYear(), date.getMonth(), date.getDay());
                    countDown = CD;
                    NowDateStr = sdf.format(c.getTime());
                }
                selectingDate = true;

            }
        });
        mcv.setOnMonthChangedListener(new OnMonthChangedListener() {
            @Override
            public void onMonthChanged(final MaterialCalendarView widget, CalendarDay date) {
                /*
                c = date.getCalendar();
                mDatePicker.updateDate(date.getYear(),date.getMonth(),date.getDay());
                countDown=CD;
                NowDateStr = sdf.format(c.getTime());
                */
            }
        });
        mcv.setTopbarVisible(false);

        mcv.addDecorator(new MCVPeriodDecorator(this));
        //mcv.addDecorator(new MCVSelectorDecorator(this));
        for (int i = 0; i <= OvulationLength / 2; i++) {
            mcv.addDecorator(new MCVOvulationDecorator(this, i));
        }
        mcv.addDecorator(new MCVTodayDecorator(this));
        countDown = 4;
        showPicker = false;

    }

    private List<Map<String, Object>> getData(String date) {
        List<Map<String, Object>> list = new ArrayList<>();

        Map<String, Object> map;
        if (date == null)
            date = NowDateStr = sdf.format(c.getTime());
        Log.v("date", date);
        JSONObject root = new JSONObject();
        try {
            root.put("UserNo", Long.parseLong(GUserNum) /*Long.parseLong(GUserNum)*/);
            root.put("DetectionDateStart", date);
            root.put("DetectionDateEnd", date);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        System.out.println("getDetections:" + root);
        JSONObject out = GlobalHelper.PostData(root, "http://120.77.255.57/ting/getDetections.php");
        System.out.println("getDetections:" + out);
        try {
            if (out.getInt("OperateResult") == 1) {
                String OperateMsg = out.getString("OperateMsg"); // 获取操作结果信息
                System.out.printf(" OperateResult : %s \n OperateMsg : %s\n", out.getInt("OperateResult"), OperateMsg);
                //JSONObject result = new JSONObject(out.getString("OperateMsg"));
                for (int i = 0; i < out.getInt("ResultCount"); i++) {
                    JSONObject historyObject = new JSONObject(out.getString("" + i));
                    map = new HashMap<>();
                    if (historyObject.get("type").equals("LH")) {
                        String temp = getResources().getString(R.string.Ovulation_more_str);
                        String temp2 = String.format(temp, historyObject.getInt("DetectionResults"));
                        if (historyObject.getInt("DetectionResults") <= 72)
                            temp2 = getString(R.string.Ovulation_near);
                        if (historyObject.getInt("DetectionResults") > 72)
                            temp2 = getString(R.string.Ovulation_far);

                        map.put("value", temp2);
                        map.put("date", historyObject.get("DetectionDate"));
                        map.put("img", R.color.zero);
                        map.put("data", "LH: " + (int) (historyObject.getDouble("RawDetectionData")) + " mIU/L");
                    } else {
                        if (historyObject.get("DetectionResults").equals("" + 0)) {
                            map.put("value", thisContext.getString(R.string.NotPregnanted_str));
                            map.put("img", R.drawable.cross);
                        } else {
                            map.put("value", thisContext.getString(R.string.Pregnanted_str));
                            map.put("img", R.drawable.check);
                        }
                        map.put("date", historyObject.get("DetectionDate"));
                        map.put("data", "HCG: " + (int) (historyObject.getDouble("RawDetectionData")) + " mIU/L");
                    }
                    list.add(map);
                }
            } else {
                System.out.println("predict error");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("detectionHistory Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        //client.connect();
        //AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        //AppIndex.AppIndexApi.end(client, getIndexApiAction());
        //client.disconnect();
    }

    public void onClickLineChart(View view) {
        exit = true;
        Intent intent = new Intent("linearAnalysisActivity");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }


    public void onSwitchCalendar(View view) {
        View rlDateSample = findViewById(R.id.rlDateSample);
        TextView textView28 = (TextView)findViewById(R.id.textView28);
        ObjectAnimator animator1 = ObjectAnimator.ofFloat(rlDateSample, "rotationX", 0, 360);
        animator1.setInterpolator(new OvershootInterpolator(1.0f));
        animator1.setDuration(800).start();
        if (flCursorWheel.getVisibility() == View.GONE) {
            flCalendar.setVisibility(View.GONE);
            flCursorWheel.setVisibility(View.VISIBLE);
            textView28.setText(getString(R.string.Other));
            SetCursorWheel(c);
        } else {
            flCalendar.setVisibility(View.VISIBLE);
            flCursorWheel.setVisibility(View.GONE);
            textView28.setText(getString(R.string.Today_str));
        }

    }

    public void onClickSwitchToday(View view){
        if (flCursorWheel.getVisibility() == View.GONE) {
            c=Calendar.getInstance();
            NowDateStr = sdf.format(c.getTime());
            SetCursorWheel(c);
            handler.post(updateDate);
            handler.post(updateDateDetail);
        }
    }
    public void onClickWheelSwitchToday(View view){
        Button btReset = (Button)findViewById(R.id.btReset);
        btReset.setBackground(getDrawable(R.drawable.today));
        cwl.setSelection(10);
    }

    public void SetCursorWheel(Calendar date) {
        System.out.println("SD:C" + sdf.format(c.getTime()));
        System.out.println("SD:date" + sdf.format(date.getTime()));
        Calendar datePointer = (Calendar) date.clone();
        datePointer.add(Calendar.DAY_OF_MONTH, -10);
        wheelItemData = new ArrayList<>();
        Calendar tempDayCalendar = Calendar.getInstance();
        try {
            tempDayCalendar.setTime(sdf.parse(FirstDay));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long firstDay = (tempDayCalendar.getTimeInMillis() / ONE_DAY_MS) % Menstruation;
        tempDayCalendar.add(Calendar.DAY_OF_MONTH, PeriodLength);
        long firstDayAfterPeriod = (tempDayCalendar.getTimeInMillis() / ONE_DAY_MS) % Menstruation - firstDay;
        long firstDayOfOvulation = DaysBeforeOvulation;
        long lastDayOfOvulation = firstDayOfOvulation + OvulationLength;
        long lastDay = firstDay + Menstruation - firstDay;
        for (int i = 0; i < 30; i++) {
            long nowDay = (datePointer.getTimeInMillis() / ONE_DAY_MS - 1) % Menstruation;
            nowDay -= firstDay;
            if (nowDay < 0)
                nowDay += Menstruation;
            if (nowDay >= 0 && nowDay < firstDayAfterPeriod) {
                if (nowDay == 0) {
                }
                wheelItemData.add(new WheelItemData(getDrawable(R.drawable.calendarview_red), datePointer.getTime()));
            } else if (nowDay >= firstDayOfOvulation && nowDay < lastDayOfOvulation) {
                if (nowDay == firstDayOfOvulation) {
                }
                wheelItemData.add(new WheelItemData(getDrawable(R.drawable.calendarview_pink), datePointer.getTime()));
            } else {
                wheelItemData.add(new WheelItemData(getDrawable(R.drawable.orangeshape), datePointer.getTime()));
            }
            datePointer.add(Calendar.DAY_OF_MONTH, 1);
        }
        cwl.setAdapter(new SimpleCycleWheelAdapter(this, wheelItemData, cwl));
        cwl.setCriticalAngle(0);
        cwl.setOnMenuSelectedListener(new CursorWheelLayout.OnMenuSelectedListener() {
            @Override
            public void onItemSelected(CursorWheelLayout parent, View view, int pos) {
                TextView tvDate = (TextView) view.findViewById(R.id.tvDate);
                SimpleCycleWheelAdapter.SetAni(view);
                Date date = null;
                try {
                    date = sdf.parse(tvDate.getText().toString());
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                c.set(date.getYear() + 1900, date.getMonth(), date.getDate());
                countDown = CD;
                NowDateStr = sdf.format(c.getTime());
                Button btReset = (Button)findViewById(R.id.btReset);
                System.out.println("pos:"+pos);
                if(pos!=10) {
                    btReset.setBackground(getDrawable(R.drawable.switch_today));
                }else {
                    btReset.setBackground(getDrawable(R.drawable.today));
                }
            }
        });
        cwl.setOnItemAngleChangeListener(new CursorWheelLayout.OnItemAngleChangeListener() {
            @Override
            public void onItemAngleChange(CursorWheelLayout parent, View view, int pos, boolean direction, float changeAngle) {
            }
        });
        System.out.println("CycleWheel:Count" + cwl.getChildCount());
        cwl.setSelection(10, false);
    }

    public void onClickShare(View view) {
        showShare();
    }

    public void onClickShowDataPicker(View view) {
        /*
        rlDataPicker.setVisibility(View.VISIBLE);
        showPicker=true;
        */
        Calendar selectedDate = c;
        Calendar startDate = Calendar.getInstance();
        //startDate.set(2013,1,1);
        Calendar endDate = Calendar.getInstance();
        //endDate.set(2020,1,1);

        //正确设置方式 原因：注意事项有说明
        startDate.set(2013, 0, 1);
        endDate.set(2020, 11, 31);
        pvPickDay = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                //pvPickDay.setText(sdf.format(date));
                c.set(date.getYear() + 1900, date.getMonth(), date.getDate());
                NowDateStr = sdf.format(c.getTime());
                //new Thread(UpdateOp).start();
                //tvTime.setText(getTime(date));
                SetCursorWheel(c);
                handler.post(updateDate);
                handler.post(updateDateDetail);
            }
        }).setLayoutRes(R.layout.pickerview_custom_day_options, new CustomListener() {
            @Override
            public void customLayout(View v) {
                //自定义布局中的控件初始化及事件处理
                final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                tvSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvPickDay.returnData();
                        pvPickDay.dismiss();
                    }
                });
                ivCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvPickDay.dismiss();
                    }
                });

            }
        })
                .setLabel("", "", "", "", "", "")
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .isCyclic(true)//是否循环滚动
                .setContentSize(24)
                .setBgColor(0xEEEEEE)//滚轮背景颜色 Night mode
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(true)//是否显示为对话框样式
                .build();
        pvPickDay.show();
    }

    public void onClickNotShowDataPicker(View view) {
        rlDataPicker.setVisibility(View.GONE);
        showPicker = false;
    }

    private void showShare() {
        try {
            saveCurrentImage();
        } catch (IOException e) {
            e.printStackTrace();
        }
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权

        oks.disableSSOWhenAuthorize();
        // title标题，印象笔记、邮箱、信息、微信、人人网、QQ和QQ空间使用
        oks.setTitle(getString(R.string.app_name));
        // titleUrl是标题的网络链接，仅在Linked-in,QQ和QQ空间使用
        oks.setTitleUrl("http://aaaaahealth.com/");
        // text是分享文本，所有平台都需要这个字段
        oks.setText(getString(R.string.ShareText));
        //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
        //oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        oks.setImagePath(Environment.getExternalStorageDirectory().toString() + "/w65/share_bitmap/myshare.png");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://aaaaahealth.com/");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment(getString(R.string.ShareComment));
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite("ShareSDK");
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://aaaaahealth.com/");
// 启动分享GUI
        oks.show(this);
    }

    private void saveCurrentImage() throws IOException {
        //获取当前屏幕的大小
        int width = getWindow().getDecorView().getRootView().getWidth();
        int height = getWindow().getDecorView().getRootView().getHeight();
        //生成相同大小的图片
        Bitmap temBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        //找到当前页面的跟布局
        View view = getWindow().getDecorView().getRootView();
        //设置缓存
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        //从缓存中获取当前屏幕的图片
        temBitmap = view.getDrawingCache();

        //输出到sd卡
        String path = Environment.getExternalStorageDirectory().toString() + "/w65/share_bitmap/";
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        File myIconFile = new File(path + "myshare.png");
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myIconFile));
        temBitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
    }

    public void onClickDetection(View view) {
        exit = true;
        Intent intent = new Intent("controlCenterActivity");
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }

    public void onClickUser(View view) {
        exit = true;
        Intent intent = new Intent("ImprovePersonalInformationActivity");
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }

    public void onClickBack(View view) {
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit = true;
            finish();
            Intent intent = new Intent("controlCenterActivity");
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
//            finish();
        }
        return false;
    }

    public void onClickShowDetection(View view) {
        ShowLocalDetection = false;
        DetectionDatetime = ((TextView) (view.findViewById(R.id.date))).getText().toString();
        startActivity(new Intent("DetectionResultActivity"));
//        finish();
    }

    @Override
    protected void onDestroy() {
        exit = true;
        super.onDestroy();
    }


    public void onClickShop(View view) {
        Intent intent = new Intent("ShoppingActivity");
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
//        finish();
    }
}
